<template>
  <div v-has="'role-query'" class="user-manager">
    <div class="query-form">
      <query-form
        :form="searchForm"
        v-model="roleForm"
        @handleQuery="handleQuery"
        @handleReset="handleReset"
      />
      <!-- <el-form
        :model="roleForm"
        label-width="120px"
        ref="query_form"
        style="display: flex"
      >
        <div class="query" style="display: flex">
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="roleForm.roleName"
              placeholder="请输入角色名称"
            />
          </el-form-item>
        </div>

        <div class="clickQuery" style="margin-left: 30px; width: 200px">
          <el-button type="primary" @click="screeningUser">查询</el-button>
          <el-button @click="query_reset">重置</el-button>
        </div>
      </el-form> -->
    </div>

    <div class="base-table">
      <list-table
        :columns="columns"
        :tableList="roleList"
        :btnList="btnList"
        @userCreate="userCreate"
        @onuserEdit="onuserEdit"
        @rolePower="rolePower"
        @userDel="userDel"
      />
      <pagination :total="total" @handleCurrentChange="handleCurrentChange" />
      <!-- <div class="action">
        <el-button type="primary" v-has="'role-create'" @click="roleAdd"
          >新增</el-button
        >
      </div>

      <el-table
        ref="multipleTableRef"
        :data="roleList"
        style="width: 100%"
        row-key="_id"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        ></el-table-column>

        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button v-has="'role-edit'" @click="roleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              v-has="'role-setting'"
              @click="rolePower(scope.row)"
              >设置权限</el-button
            >
            <el-popconfirm
              confirm-button-text="Yes"
              cancel-button-text="No"
              title="Are you sure to delete?"
              @confirm="roleDel(scope.row)"
            >
              <template #reference>
                <el-button v-has="'role-delete'" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="page">
        <el-pagination
          layout=" prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div> -->
    </div>

    <el-dialog v-model="showMadol" :title="title">
      <el-form ref="dialogRoleForm" :model="roleForm" :rules="rules">
        <el-form-item label="用户名称" prop="roleName">
          <el-input v-model="roleForm.roleName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="powerShow" title="权限设置">
      <el-form :model="powerForm">
        <el-form-item label="角色名称">
          {{ rolePowerName }}
        </el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            ref="dataTree"
            :data="dataList"
            show-checkbox
            node-key="_id"
            default-expand-all
            :props="{ children: 'children', label: 'menuName' }"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="powerShow = false">取消</el-button>
          <el-button type="primary" @click="powerYes">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 制作权限的分配流程
// step1 制作对应的弹窗并且把菜单数据渲染到弹窗中
import api from './../api'
import utils from './../utils/utils.js'
import message from '../utils/message.js'
import storage from "../utils/storage.js";
import { ref, reactive, toRaw, nextTick } from 'vue'
// 显示搜索表单
const searchForm = [
  {
    type: 'input',
    label: '角色名称',
    prop: 'roleName',
    placeholder: '请输入角色名称'
  },
]
// 显示按钮
let btnList = reactive({
  tbTopBtn: [
    {
      type: 'primary',
      text: '新增',
      id: 1,
      has: 'user-create',
    },
  ],
  tableBtn: [
    {
      type: '',
      text: '编辑',
      id: 3,
    },
    {
      type: 'primary',
      text: '设置权限',
      id: 5,
    },
    {
      type: 'danger',
      text: '删除',
      id: 2,
    },
  ],
})
// 定义页面页码
let total = ref(1)
// 定义记录用户行为
let action = ref('create')
// 定义创建弹窗显示
let showMadol = ref(false)
// 定义创建弹窗标题
let title = ref('角色新增')
// 定义创建弹窗表单节点
const dialogRoleForm = ref(null)
// 定义设置权限弹窗显示
let powerShow = ref(false)
// 定义权限表单
let powerForm = reactive({})
// 定义权限列表
let dataList = ref([])
let rolePowerName = ref(null)
let dataTree = ref(null)
// 弹窗表单校验
let rules = reactive({
  roleName: [
    {
      required: true,
      message: "请输入菜单名称",
      trigger: "blur",
    },
    {
      min: 2,
      max: 10,
      message: "长度在2-8个字符",
      trigger: "blur",
    },
  ],
})
// 定义请求列表
let roleForm = reactive({
  roleName: null,
  remark: null
})
// 定义初始化的分页设置
let pager = reactive({
  pageNum: 1,
  pageSize: 10
})
// 定义角色列表
let roleList = ref([])
// 用户权限菜单列表请求
const getPermissionList = async () => {
  let { menuList } = await api.getPermissionList()
  dataList.value = menuList
}
getPermissionList()
// 定义菜单映色表
let actionMap = reactive({})
// 定义建立映色表的方法
const getAtionBuild = (val) => {
  // val 是请求过来的数据
  let map = {}
  const deep = (arr) => {
    while (arr.length) {
      let item = arr.pop()
      // item代表每个对象 一级菜单
      if (item.children && item.action) {
        // 代表二级菜单
        map[item._id] = item.menuName
      }
      if (item.children && !item.action) {
        // 一级菜单
        deep(item.children)
      }
    }
  }
  deep(val)
  actionMap = map
}
getAtionBuild(storage.getItem('menuList'))
// 定义动态表格--格式
let columns = reactive([
  {
    label: '角色名称',
    prop: 'roleName'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '权限列表',
    prop: 'permissionList',
    formatter: (row, colum, value) => {
      let halfCheckedKey = value.halfCheckedKeys || []
      //   显示数组
      let arr = []
      //   当前对象的id
      // 查找 actionMap
      halfCheckedKey.map(key => {
        let name = actionMap[key]
        if (key && name) {
          arr.push(name)
        }
      })
      return arr.join('.')
    }
  },
  {
    label: '更新时间',
    prop: 'updateTime',
    formatter: (row, colum, value) => {
      return utils.formateDate(new Date(value))
    }
  },
  {
    label: '创建时间',
    prop: 'createTime',
    formatter: (row, colum, value) => {
      return utils.formateDate(new Date(value))
    }
  }
])

// 定义角色请求
const getRolesList = async () => {
  let data = { ...roleForm, ...pager }
  let { list, page } = await api.getRolesList(data)
  roleList.value = list
  total.value = page.total
}
getRolesList()
// 定义表单重置方法
const resetForm = () => {
  dialogRoleForm.value.resetFields()
}
// 新增
const userCreate = () => {
  showMadol.value = !showMadol.value
}
// 弹窗取消
const handleCancel = () => {
  resetForm()
  showMadol.value = !showMadol.value
}
// 弹窗确定
const handleSubmit = () => {
  dialogRoleForm.value.validate((vaild) => {
    if (vaild) {
      let data = toRaw(roleForm)
      data.action = action.value
      api.postRolesOperate(data).then(res => {
        showMadol.value = !showMadol.value
        message.message('提交成功!', 'success')
        resetForm()
        getRolesList()
      })
    }
  })
}
// 编辑
const onuserEdit = (row) => {
  title.value = '角色编辑'
  action.value = 'edit'
  showMadol.value = !showMadol.value
  nextTick(() => {
    Object.assign(roleForm, row.row)
  })
}
// 设置权限
const rolePower = async (row) => {
  powerForm = toRaw(row)
  let { checkedKeys } = row.permissionList
  rolePowerName.value = powerForm.roleName
  powerShow.value = !powerShow.values
  setTimeout(() => {
    //   获取节点mounted 确保节点一定获取
    dataTree.value.setCheckedKeys(checkedKeys)
  })
}
// 编辑权限弹窗确定
const powerYes = () => {
  let data = {
    _id: powerForm._id,
    permissionList: {
      checkedKeys: dataTree.value.getCheckedKeys(false),
      halfCheckedKeys: dataTree.value.getHalfCheckedKeys(true)
    }
  }
  api.postRolesUpdatePermission(data).then(res => {
    message.message('设置成功!', 'success')
    powerShow.value = !powerShow.value
    getRolesList()
  })
}
// 删除
const userDel = (row) => {
  action.value = 'delete'
  let data = { _id: row._id, action: action.value }
  api.postRolesOperate(data).then(res => {
    message.message('删除成功!', 'success')
    getRolesList()
  })
}
// 查询
const handleQuery = (val) => {
  let data = {
    roleName: val.value.roleName
  }
  api.getRolesList(data).then(res => {
    roleList.value = res.list
    message.message('查询成功!', 'success')
  })
}
// 重置
const handleReset = (val) => { message.message('重置成功!', 'success') }
// 定义页面列表切换事件
const handleCurrentChange = (val) => {
  getRolesList()
}

</script>

<style lang="scss" scoped>
.user-manager {
  .query-form {
    border-radius: 5px;
    background-color: #fff;
    padding: 20px;
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .base-table {
    margin-top: 20px;
    border-radius: 5px;
    .action {
      padding: 20px;
      background-color: #fff;
      border-bottom: 1px solid #eef0f3;
    }
    .page {
      margin: 10px auto;
      float: right;
    }
  }
}
</style>